//
//  MusicDetailViewController.m
//  On The Load
//
//  Created by 许嘉成 on 15/11/14.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "MusicDetailViewController.h"


#import "MusicDetailViewController.h"
#import "AppTools.h"
#import "SecondTableViewCell.h"
#import "ThirdTableViewCell.h"
#import "FourthTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "CoreDataManager.h"
#import "MBProgressHUD+show.h"
#import "XJCMusciModel.h"
#import "MusicModel.h"
//#import "UMSocial.h"

@interface MusicDetailViewController ()<UITableViewDataSource,UITableViewDelegate,collectMusic,shareMusic>

@property(nonatomic,retain)UITableView *musicDTV;//tableview
@property(nonatomic,retain)NSMutableArray *musicArray;//音乐数组
//第一块儿的视图
@property(nonatomic,retain)UIImageView *userImgView;//用户头像
@property(nonatomic,retain)UILabel *userName;//用户名
@property(nonatomic,retain)UIImageView *backImgView;//背景图
@property(nonatomic,retain)UILabel *followLabel;//关注数
@property(nonatomic,retain)UILabel *aLabel;//"被关注"
@property(nonatomic,retain)UIView *playBtn;//播放按钮视图
@property(nonatomic,retain)UIImageView *playImgView;//播放按钮视图(小)
@property(nonatomic,retain)UILabel *timeLabel;//时间
@property(nonatomic,retain)NSTimer *timer;
@property(nonatomic,retain)UILabel *titleLabel;//歌名
@property(nonatomic,retain)UILabel *viewCountLabel;//收听次数
@property(nonatomic,copy)NSString *currentSource;//当前播放的音乐源

@property(nonatomic,retain)STKDataSource *dataSource;
@property(nonatomic,assign)BOOL start;



@end

@implementation MusicDetailViewController

+(instancetype)sharePlayerViewController
{
    static MusicDetailViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        player = [[MusicDetailViewController alloc] init];
        
    });
    return player;
}

-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    //头部视图
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    headerView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    [self.view addSubview:headerView];
    //设置标题
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    label.text  = @"Music";
    label.textColor = [UIColor colorWithRed:0.545 green:0.902 blue:0.779 alpha:1.000];
    label.font = [UIFont fontWithName:@"Helvetica-Bold" size:20*SCALEW];
    label.center = CGPointMake(headerView.center.x, 40*SCALEH);
    [headerView addSubview:label];
    
    //左侧返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10, 25, 30, 30);
    [backBtn setImage:[UIImage imageNamed:@"back-icon@2x.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:backBtn];
    
    
    //音乐数组初始化
    self.musicArray = [NSMutableArray array];
    
    //    //设置导航栏背景
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"J64HV%@([]A}M(S6KR[T$A5.jpg"] forBarMetrics:UIBarMetricsDefault];
    //    self.navigationItem.title = @"Music";
    //调用创建视图
    [self createTableView];
    //播放音乐
    [self.player play:self.musicM.source];
    NSLog(@"111");
    
}
//重写set方法
-(void)setDetailId:(NSString *)detailId
{
    _detailId = detailId;
    
    
    //请求数据
    [AppTools getAFN:[NSString stringWithFormat:@"http://echosystem.kibey.com/sound/info?sound_id=%@",self.detailId]  andpara:nil andBlock:^(id result) {
        
        [self.musicArray removeAllObjects];
        NSMutableDictionary *bigDic = result;
        NSMutableDictionary *resultDic = [bigDic objectForKey:@"result"];
        XJCMusciModel *musicM = [[XJCMusciModel alloc]init];
        [musicM setValuesForKeysWithDictionary:resultDic];
        [self.musicArray addObject:musicM];
        NSLog(@"!!%@",self.musicArray);
        [self.musicDTV reloadData];
        
        //判断跳进来的歌曲是否为之前播放的
        if (self.currentSource != detailId) {
            [self.player play:self.musicM.source];
            self.playBtn.hidden = YES;
            self.currentSource = detailId;
        }
        //定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];

    } andfailBlock:^(id result) {
        
    }];
    
    
}
//左侧按钮触发事件
-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
//创建视图
-(void)createTableView
{
    self.musicDTV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64) style:UITableViewStyleGrouped];
    self.musicDTV.dataSource = self;
    self.musicDTV.delegate = self;
    [self.view addSubview:self.musicDTV];
    //创建播放器
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;
    
    [self createSection1];
}
//创建第一个区的视图
-(void)createSection1
{
    self.userImgView = [[UIImageView alloc]initWithFrame:CGRectMake(10*WIDTH/375, 15*HEIGHT/667, 50*WIDTH/375, 50*WIDTH/375)];
    //    self.userImgView.backgroundColor = [UIColor colorWithRed:0.162 green:0.798 blue:0.372 alpha:1.000];
    self.userImgView.layer.masksToBounds = YES;
    self.userImgView.layer.cornerRadius = self.userImgView.frame.size.width/2;
    
    self.userName = [[UILabel alloc]initWithFrame:CGRectMake(self.userImgView.frame.origin.x+self.userImgView.frame.size.width+5, self.userImgView.frame.origin.y+10, 250*WIDTH/375, 30*HEIGHT/667)];
    self.userName.textColor = [UIColor colorWithWhite:0.600 alpha:1.000];
    //    self.userName.backgroundColor = [UIColor colorWithRed:0.502 green:0.000 blue:1.000 alpha:1.000];
    self.userName.font = [UIFont systemFontOfSize:18*SCALEH];
    
    self.backImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.userImgView.frame.origin.y+self.userImgView.frame.size.height+10, WIDTH, 400*HEIGHT/667)];
    //    self.backImgView.backgroundColor = [UIColor colorWithRed:0.187 green:1.000 blue:0.350 alpha:1.000];
    self.backImgView.userInteractionEnabled = YES;
    //添加轻拍手势
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(StopPlay)];
    [self.backImgView addGestureRecognizer:tap1];
    
    UIView *blackV = [[UIView alloc]initWithFrame:CGRectMake(0, self.backImgView.frame.size.height-20*HEIGHT/667, WIDTH, 20*HEIGHT/667)];
    blackV.backgroundColor = [UIColor blackColor];
    blackV.alpha = 0.7;
    [self.backImgView addSubview:blackV];
    
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(5*WIDTH/375, 2, 100*WIDTH/375, 18*HEIGHT/667)];
    self.timeLabel.font = [UIFont systemFontOfSize:15*SCALEH];
    self.timeLabel.textColor = [UIColor whiteColor];
    //    self.timeLabel.backgroundColor = [UIColor whiteColor];
    [blackV addSubview:self.timeLabel];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.timeLabel.frame.origin.x+self.timeLabel.frame.size.width, self.timeLabel.frame.origin.y, 170*WIDTH/375, self.timeLabel.frame.size.height)];
    //    self.titleLabel.backgroundColor = [UIColor redColor];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:15*SCALEH];
    [blackV addSubview:self.titleLabel];
    
    self.viewCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.titleLabel.frame.origin.x+self.titleLabel.frame.size.width, self.titleLabel.frame.origin.y, 50*WIDTH/375, self.titleLabel.frame.size.height)];
    self.viewCountLabel.textColor = [UIColor whiteColor];
    self.viewCountLabel.font = [UIFont systemFontOfSize:15*SCALEH];
    self.viewCountLabel.textAlignment = NSTextAlignmentRight;
    [blackV addSubview:self.viewCountLabel];
    
    UILabel *bLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.viewCountLabel.frame.origin.x+self.viewCountLabel.frame.size.width, self.viewCountLabel.frame.origin.y, 50*WIDTH/375, self.viewCountLabel.frame.size.height)];
    bLabel.text = @"次收听";
    bLabel.textColor = [UIColor whiteColor];
    bLabel.font = [UIFont systemFontOfSize:15*SCALEH];
    [blackV addSubview:bLabel];
    
    self.aLabel = [[UILabel alloc]initWithFrame:CGRectMake(280*WIDTH/375, self.userName.frame.origin.y+10, 40*WIDTH/375, 15)];
    self.aLabel.font = [UIFont systemFontOfSize:13*SCALEH];
    self.aLabel.text = @"被关注";
    //    label.backgroundColor = [UIColor colorWithRed:0.911 green:1.000 blue:0.922 alpha:1.000];
    self.aLabel.textColor = [UIColor colorWithWhite:0.702 alpha:1.000];
    
    self.followLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.aLabel.frame.origin.x+self.aLabel.frame.size.width+1, self.aLabel.frame.origin.y, 50*WIDTH/375, self.aLabel.frame.size.height)];
    //    self.followLabel.backgroundColor = [UIColor colorWithRed:1.000 green:0.792 blue:0.916 alpha:1.000];
    self.followLabel.font = [UIFont systemFontOfSize:13*SCALEH];
    self.followLabel.textColor = [UIColor colorWithRed:0.545 green:0.902 blue:0.779 alpha:1.000];
    
    
    
    self.playBtn = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50*WIDTH/375, 50*WIDTH/375)];
    self.playBtn.backgroundColor = [UIColor blackColor];
    self.playBtn.center = self.backImgView.center;
    self.playBtn.alpha = 0.6;
    self.playBtn.hidden = YES;
    self.playBtn.layer.masksToBounds = YES;
    self.playBtn.layer.cornerRadius = self.playBtn.frame.size.width/2;
    self.playBtn.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(playMusic)];
    [self.playBtn addGestureRecognizer:tap2];
    
    UIImageView *playImgView = [[UIImageView alloc]initWithFrame:CGRectMake(10*WIDTH/275, 12.5*WIDTH/375, 25*WIDTH/375, 25*WIDTH/375)];
    playImgView.image = [UIImage imageNamed:@"iconfont-iconfontbofang-5.png"];
    //    playImgView.backgroundColor = [UIColor colorWithRed:0.400 green:1.000 blue:0.800 alpha:1.000];
    [self.playBtn addSubview:playImgView];
}
#pragma mark -- 播放器方法
//播放方法
-(void)playMusic
{
    self.player.state = STKAudioPlayerStatePlaying;
    self.playBtn.hidden = YES;
    [self.player resume];
}
//暂停方法
-(void)StopPlay
{
    self.player.state = STKAudioPlayerStatePaused;
    self.playBtn.hidden = NO;
    [self.player pause];
}
//每隔一秒调用该方法
-(void)track
{
    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    NSLog(@"proMin = %ld proSec = %ld",proMin, proSec);
}

#pragma mark -- tableview协议方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XJCMusciModel * musicM = [[XJCMusciModel alloc] init];
    NSLog(@"!@%@",self.musicArray);
    if (self.musicArray.count != 0) {
        musicM = [self.musicArray objectAtIndex:indexPath.row];
    } else {
        musicM = nil;
    }
    if (indexPath.section == 0) {
        NSString *cellIdentifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        //视图加入
        [cell.contentView addSubview:self.userImgView];
        [cell.contentView addSubview:self.userName];
        [cell.contentView addSubview:self.backImgView];
        [cell.contentView addSubview:self.aLabel];
        [cell.contentView addSubview:self.followLabel];
        [cell.contentView addSubview:self.playBtn];
        //赋值过程
        [self.userImgView sd_setImageWithURL:[NSURL URLWithString:[musicM.user objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"whiteLogo.png"]];
        self.userName.text = [musicM.user objectForKey:@"name"];
        [self.backImgView sd_setImageWithURL:[NSURL URLWithString:musicM.pic_1080] placeholderImage:[UIImage imageNamed:@"whiteLogo.png"]];
        self.titleLabel.text = musicM.name;
        //收听数如果过万 变成x.x万
        CGFloat replay = [musicM.view_count floatValue];
        if (replay > 0) {
            
            NSString *replayStr = [NSString stringWithFormat:@"%.0f", replay];
            if (replay / 10000 >= 1.0) {
                replayStr = [NSString stringWithFormat:@"%.1f万", replay / 10000];
            }
            self.viewCountLabel.text = replayStr;
        }
        //关注数如果过万 变成x.x万
        CGFloat replay1 = [[musicM.user objectForKey:@"followed_count"] floatValue];
        if (replay1 > 0) {
            
            NSString *replayStr = [NSString stringWithFormat:@"%.0f", replay1];
            if (replay1 / 10000 >= 1.0) {
                replayStr = [NSString stringWithFormat:@"%.1f万", replay / 10000];
            }
            self.followLabel.text = replayStr;
        }
        
        
        //设置cell点击效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1)
    {
        NSString *cellIdentifier = @"cell";
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[SecondTableViewCell  alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        //代理
        cell.collectDelegate = self;
        cell.shareDelegate = self;
        //设置cell点击效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.musicM = musicM;
        return cell;
    }else if(indexPath.section == 2)
    {
        NSString *cellIdentifier = @"cell";
        ThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[ThirdTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        //设置cell点击效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.musicM = musicM;
        return cell;
        
    }else
    {
        NSString *cellIdentifier = @"cell";
        FourthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[FourthTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        //设置cell点击效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.musicM = musicM;
        return cell;
    }
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    XJCMusciModel *musicM = [[XJCMusciModel alloc]init];
    if (self.musicArray.count != 0) {
        self.musicM = [self.musicArray objectAtIndex:indexPath.row];
    } else {
        self.musicM = nil;
    }

    if (indexPath.section == 0) {
        return 475*SCALEH;
    }else if (indexPath.section == 1)
    {
        return 50*SCALEH;
    }else if(indexPath.section == 2){
        return 100*SCALEH;
    }else
    {
        
        return [AppTools heightForCell:self.musicM.info andwide:WIDTH-10*2]+80*HEIGHT/667;
    }
}

#pragma mark -- SecondCell DataSource
- (void)collectMusic:(UIButton *)collectBtn{
    
    if (collectBtn.selected == NO) {
        
        [MBProgressHUD showCollectGIFWithText:@"收藏(ฅ>ω<*ฅ)成功"];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"MusicModel" inManagedObjectContext:[CoreDataManager shareManager].managedObjectContext];
        
        //参数1:通过一个实体描述对象来初始化
        //参数2:叫给谁去管理(数据管理器)
        MusicModel *musicM = [[MusicModel alloc] initWithEntity:entity insertIntoManagedObjectContext:[CoreDataManager shareManager].managedObjectContext];
        musicM.name = _musicM.name;
        musicM.id = _musicM.id;
        musicM.pic_640 = _musicM.pic_640;
        musicM.channel = [_musicM.channel objectForKey:@"name"];
    }else{
        
        [MBProgressHUD showGIFWithText:@"取消%>_<%收藏"];
        
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicModel"];
        request.predicate = [NSPredicate predicateWithFormat:@"name = %@", _musicM.name];
        
        //向数据管理器发送请求
        NSArray *array = [[CoreDataManager shareManager].managedObjectContext executeFetchRequest:request error:nil];
        for (MusicModel *music in array) {
            [[CoreDataManager shareManager].managedObjectContext deleteObject:music];
        }
    }
    
    collectBtn.selected = !collectBtn.selected;
    
    [[CoreDataManager shareManager] saveContext];
}
#pragma mark -- shareMusic DataSource
- (void)shareMusic{
    
    
    
//    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"507fcab25270157b37000010"
//                                      shareText:self.musicM.source
//                                     shareImage:self.musicM.pic_640
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToTwitter, nil]
//                                       delegate:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
